package com.iflysse.servlet.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iflysse.pojo.UserInfo;
import com.iflysse.service.UserInfoService;
import com.iflysse.utils.Md5;
import com.iflysse.utils.PagerBean;

/**
 * Servlet implementation class UserInfoDisServlet
 */
@WebServlet("/user/userInfo.do")
public class UserInfoDisServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private UserInfoService service = new UserInfoService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setContentType("charset=utf-8;");
		resp.setCharacterEncoding("utf-8");

		String mtd = req.getParameter("method");
		if ("load".equals(mtd)) {
			load(req, resp);
		} else if ("del".equals(mtd)) {
			delUser(req, resp);
		} else if ("initForm".equals(mtd)) {
			initForm(req, resp);
		} else if ("insert".equals(mtd)) {
			insert(req, resp);
		} else if ("update".equals(mtd)) {
			update(req, resp);
		} else if ("findById".equals(mtd)) {
			findByIdOrName(req, resp);
		} else if ("findByName".equals(mtd)) {
			findByName(req, resp);
		} else {
			req.getRequestDispatcher(
					"/WEB-INF/views/userinfo/userInfoIndex.jsp").forward(req,
					resp);
		}
	}

	private void findByName(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		// TODO Auto-generated method stub
		resp.setContentType("text/plain;charset=utf-8");
		String name = req.getParameter("username");
//		System.out.println("sadfasaf" + name);
		List<UserInfo> user = service.findUserByName(name);
//		System.out.print(user.size());
		int flag = 0;
		if (user.size() != 0) {
			flag = 1;
		}
		PrintWriter writer=resp.getWriter();
		writer.write(flag+"");
		writer.flush();
	}

	private void findByIdOrName(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		if (Integer.parseInt(req.getParameter("selectednum")) == 1) {
			String id = req.getParameter("findValue");
			// System.out.println(id);
			int userid = Integer.parseInt(id);
			UserInfo user = service.findUserById(userid);
			// System.out.println(user);
			PagerBean<UserInfo> pBean = new PagerBean<UserInfo>();
			pBean.setPage(1);
			pBean.setPageSize(10);
			pBean.setTotal(service.findUserTotalById(userid));

			List<UserInfo> list = new ArrayList<UserInfo>();
			list.add(user);
			pBean.setRows(list);

			print2Page(resp, pBean.toString());

		} else {
			String name = req.getParameter("findValue");

			List<UserInfo> user = service.findUserByName(name);

			PagerBean<UserInfo> pBean = new PagerBean<UserInfo>();
			pBean.setPage(1);
			pBean.setPageSize(10);
			// List<UserInfo> list = new ArrayList<UserInfo>();
			// list.add(user);
			pBean.setRows(user);
			pBean.setTotal(service.findUserTotalByName(name));
			print2Page(resp, pBean.toString());

		}

	}

	private void update(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		String id = req.getParameter("userid");
		int userid = Integer.parseInt(id);
		String username = req.getParameter("username");
		String tel = req.getParameter("tel");
		String email = req.getParameter("email");
		String status = req.getParameter("status");
		String psw = Md5.mD5(req.getParameter("psw"));
		UserInfo user = new UserInfo();
		user.setUserid(userid);
		user.setUsername(username);
		user.setTel(tel);
		user.setEmail(email);
		user.setStatus(status);
		user.setPsw(psw);

		service.updateUser(user);
		resp.sendRedirect("/manger_v2.0/user/userInfo.do");

	}

	private void insert(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
//		String id = req.getParameter("userid");
//		int userid = Integer.parseInt(id);
		String username = req.getParameter("username");
		String tel = req.getParameter("tel");
		String email = req.getParameter("email");
		String status = req.getParameter("status");
		String psw = req.getParameter("psw");
		UserInfo user = new UserInfo();
//		user.setUserid(userid);
		user.setUsername(username);
		user.setTel(tel);
		user.setEmail(email);
		user.setStatus(status);
		user.setPsw(Md5.mD5(psw));//使用md5加密

		service.addUser(user);
		resp.sendRedirect("/manger_v2.0/user/userInfo.do");
	}

	/**
	 *
	 * @author: Administrator
	 * @createTime: 2014年11月17日 下午3:59:42
	 * @history:
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 *             void
	 */
	private void initForm(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String id = req.getParameter("userid");
		int userid = Integer.parseInt(id);
		UserInfo user = null;
		if (userid > 0) {
			user = service.findUserById(userid);
		} else {
			user = new UserInfo();
		}
		req.setAttribute("user", user);
		req.getRequestDispatcher("/WEB-INF/views/userinfo/form.jsp").forward(
				req, resp);
	}

	/**
	 *
	 * @author: Administrator
	 * @createTime: 2014年11月17日 下午3:33:39
	 * @history:
	 * @param req
	 * @param resp
	 * @throws IOException
	 *             void
	 */
	private void delUser(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		String useridsString = req.getParameter("userids");

		String[] userids = useridsString.split(",");
//		System.out.print(userids.length);
		for (int i = 0; i < userids.length; i++) {
			int userid = Integer.parseInt(userids[i]);
//			System.out.print(userid);
			service.delUserById(userid);
		}

		print2Page(resp, "{\"msg\":\"删除成功\"}");
	}

	/**
	 *
	 * @author: Administrator
	 * @createTime: 2014年11月17日 上午11:26:50
	 * @history:
	 * @param req
	 * @param resp
	 * @throws IOException
	 *             void
	 */
	private void load(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		PagerBean<UserInfo> pager = new PagerBean<UserInfo>();
		int page = 1, pageSize = 10;
		try {
			page = Integer.parseInt(req.getParameter("page"));
			pageSize = Integer.parseInt(req.getParameter("rows"));
		} catch (NumberFormatException ex) {

		}
		pager.setPage(page);
		pager.setPageSize(pageSize);
		pager = service.findUserPager(pager);
		print2Page(resp, pager.toString());
	}

	/**
	 *
	 * @author: Administrator
	 * @createTime: 2014年11月17日 下午3:31:20
	 * @history:
	 * @param resp
	 * @param pager
	 * @throws IOException
	 *             void
	 */
	private void print2Page(HttpServletResponse resp, String json)
			throws IOException {
		resp.setContentType("application/json;charset=UTF-8");
		Writer writer = resp.getWriter();
		writer.write(json);
		writer.flush();
	}

}